package com.isesol.ime.service;

import com.alibaba.fastjson.*;
import com.isesol.arch.common.mq.*;
import com.isesol.ime.*;
import com.isesol.ime.dal.mapper.*;
import com.isesol.ime.dal.model.*;
import lombok.extern.slf4j.*;
import org.apache.commons.lang3.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;

import javax.annotation.*;
import java.util.*;

/**
 * 反馈
 *
 * @author peter zhang
 */
@Component
@Slf4j
public class FeedBackService{

	@Resource
	SubscriptionMapper subscriptionMapper;

	@Resource
	MessageMapper messageMapper;

	@Resource
	SubscriptionFeedbackMapper subscriptionFeedbackMapper;
	@Resource
	SubFeedbackService subFeedbackService;

	@Resource
	SubscriptionService subscriptionService;

	@Autowired(required = false)
	MsgSender msgSender;

	public void consume(String body) throws Exception{

		Map<String, String> map = JSON.parseObject(body, Map.class);

		String msgContent = map.get("messageContent");
		if (StringUtils.isBlank(msgContent) || !msgContent.startsWith("{")){
			return;
		}
		Map<String, String> messageContentMap = JSON.parseObject(msgContent, Map.class);

		String machineId = messageContentMap.get("machineId");
		String cmdId     = messageContentMap.get("cmdId");
		String orderType = messageContentMap.get("orderType");

		String[] content = cmdId.split("\\|");

		if (Constant.DOWNLOAD_FEEDBACK.equals(content[0])){
			log.info("【Download feedback】 body={}", body);
			String subId = content[1];
			log.info("【Send first FrequencyOrder】 machineId={}", machineId);
			subscriptionService.sendFrequencyOrder(Long.parseLong(subId));
		} else if (Constant.FREQUENCY_FEEDBACK.equals(content[0])){
			log.info("【FrequencyOrder】 feedback body={}", body);
			String                 subId                  = content[1];
			SubscriptionFeedbackDO subscriptionFeedbackDO = subscriptionFeedbackMapper.findBySubId(Long.parseLong(subId));
			subscriptionFeedbackDO.setFeedback("1");
			subscriptionFeedbackMapper.update(subscriptionFeedbackDO);

			SubscriptionDO subscriptionDO = subscriptionMapper.getById(subscriptionFeedbackDO.getSubId());

			MessageDO messageDO = messageMapper.getById(subscriptionDO.getMsgId());

			Long newSubId = subscriptionFeedbackMapper.
					findOneByMachineIdAndRuleName(machineId, messageDO.getRuleName());
			if (null != newSubId){
				log.info("【Send next FrequencyOrder】,machineId={},newSubId={}",
				         machineId, newSubId);
				subscriptionService.sendFrequencyOrder(newSubId);
			}else{
				log.info("【All FrequencyOrder success】,machineId={}",
				         machineId);
			}

		}
	}
}
